﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static ConsoleApp1.AlertManager;


namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            Example example = new Example();

            example.ProcessAlert();

            Console.ReadLine();
        }

    }


    public class AlertManager : IDisposable
    {
        public enum AlertLevel
        {
            SSS = 1,    // 最高级别
            SS = 2,
            S = 3,
            A = 4,
            LowBattery = 5,     // 低电
            Controller = 6      // 智能控电器
        }
        private class AlertRequest : IComparable<AlertRequest>
        {
            public string Id { get; set; }                // 唯一标识
            public string Message { get; set; }           // 播报内容
            public AlertLevel Level { get; set; }         // 异常级别
            public DateTime CreateTime { get; set; }      // 创建时间
            public bool IsResolved { get; set; }          // 是否已解决
            public bool IsPlaying { get; set; }           // 是否正在播放
            public int Duration { get; set; }             // 播放持续时间(ms)

            public int CompareTo(AlertRequest other)
            {
                if (other == null) return 1;

                // 首先按优先级排序
                int levelCompare = ((int)Level).CompareTo((int)other.Level);
                if (levelCompare != 0) return levelCompare;

                // 同级别按时间排序
                return CreateTime.CompareTo(other.CreateTime);
            }
        }

        private readonly PriorityQueue<AlertRequest> _alertQueue;

        private readonly CancellationTokenSource _cts;
        private AlertRequest _currentPlaying;
        private readonly object _lockObj = new object();
        private volatile bool _needsRecheck = false;
        private CancellationTokenSource _playingCts;
        private readonly object _playingCtsLock = new object();

        public AlertManager()
        {
            _alertQueue = new PriorityQueue<AlertRequest>();
            
            _cts = new CancellationTokenSource();

            // 启动处理线程
            Task.Run(ProcessAlertsAsync);
        }

        // 添加新的异常
        public void AddAlert(string id, string message, AlertLevel level, int duration)
        {
            var request = new AlertRequest
            {
                Id = id,
                Message = message,
                Level = level,
                CreateTime = DateTime.Now,
                IsResolved = false,
                IsPlaying = false,
                Duration = duration
            };

            try
            {
                lock (_lockObj)
                {
                    // 检查是否需要打断当前播放
                    if (_currentPlaying != null && (int)level < (int)_currentPlaying.Level)
                    {
                        Console.WriteLine($"收到更高优先级警报，打断当前播放: {message}");
                        _playingCts.Cancel();
                        _currentPlaying = null;
                    }
                    else
                    {
                        _alertQueue.Enqueue(request);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加警报异常: {ex.Message}");
            }
        }

        // 处理异常解决
        public void ResolveAlert(string id)
        {
            try
            {
                lock (_lockObj)
                {
                    // 检查当前播放
                    if (_currentPlaying?.Id == id)
                    {
                        _currentPlaying.IsResolved = true;
                        _needsRecheck = true;
                    }

                    // 移除队列中已解决的异常
                    _alertQueue.RemoveAll(x => x.Id == id);
                    Console.WriteLine($"解决警报: {id}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"解决警报异常: {ex.Message}");
            }
        }

        private async Task ProcessAlertsAsync()
        {
            while (!_cts.Token.IsCancellationRequested)
            {
                try
                {
                    if (_currentPlaying != null)
                    {
                        // 检查当前播放是否需要停止
                        if (_currentPlaying.IsResolved || _needsRecheck)
                        {
                            _currentPlaying = null;
                            _needsRecheck = false;
                            continue;
                        }

                        // 等待当前播放完成
                        await Task.Delay(100);
                        continue;
                    }

                    // 获取下一个要播放的警报
                    AlertRequest nextAlert = null;
                    lock (_lockObj)
                    {
                        if (_alertQueue.TryDequeue(out var alert) && !alert.IsResolved)
                        {
                            nextAlert = alert;
                        }
                    }

                    if (nextAlert != null)
                    {
                        await PlayAlertAsync(nextAlert);
                    }
                    else
                    {
                        await Task.Delay(100);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理警报异常: {ex.Message}");
                    await Task.Delay(1000);
                }
            }
        }

        private async Task PlayAlertAsync(AlertRequest alert)
        {
            try
            {

                lock (_lockObj)
                {
                    if (alert.IsResolved)
                    {
                        return;
                    }
                    alert.IsPlaying = true;
                    _currentPlaying = alert;
                }

                Console.WriteLine($"开始播报: {alert.Message}, 级别: {alert.Level}");
                //await _voiceDevice.SendMessageAsync(alert.Message);
                using (var cts = new CancellationTokenSource())
                {
                    lock (_playingCtsLock)
                    {
                        _playingCts?.Dispose();
                        _playingCts = cts;
                    }

                    try
                    {
                        // 等待播放完成，可被打断
                        if (!alert.IsResolved)
                        {
                            await Task.Delay(alert.Duration, cts.Token);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        Console.WriteLine($"播报被打断: {alert.Message}");
                    }
                }
                // 等待播放完成


                lock (_lockObj)
                {
                    if (_currentPlaying == alert)
                    {
                        _currentPlaying = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"播报异常: {ex.Message}");
                lock (_lockObj)
                {
                    if (_currentPlaying == alert)
                    {
                        _currentPlaying = null;
                    }
                }
            }
        }

        public void Dispose()
        {
            _cts.Cancel();
            _cts.Dispose();
        }
    }

    // 优先级队列实现
    public class PriorityQueue<T> where T : IComparable<T>
    {
        private readonly object _lock = new object();
        private readonly List<T> _list = new List<T>();

        public void Enqueue(T item)
        {
            lock (_lock)
            {
                _list.Add(item);
                _list.Sort();  // 较小的值（高优先级）排在前面
            }
        }

        public bool TryDequeue(out T item)
        {
            lock (_lock)
            {
                if (_list.Count > 0)
                {
                    item = _list[0];
                    _list.RemoveAt(0);
                    return true;
                }
                item = default;
                return false;
            }
        }

        public void RemoveAll(Predicate<T> match)
        {
            lock (_lock)
            {
                _list.RemoveAll(match);
            }
        }

        public int Count
        {
            get { lock (_lock) { return _list.Count; } }
        }
    }

    // 使用示例
    public class Example
    {
        private readonly AlertManager _alertManager;

        public Example()
        {
            _alertManager = new AlertManager();
        }

        public async void ProcessAlert()
        {
            // 添加异常
            _alertManager.AddAlert(
                id: "alert1",
                message: "发现火情",
                level: AlertLevel.SS,
                duration: 5000
            );
            await Task.Delay(1000);
            _alertManager.AddAlert(
               id: "alert2",
               message: "发现火情2",
               level: AlertLevel.SSS,
               duration: 3000
           );
            _alertManager.AddAlert(
               id: "alert1",
               message: "发现火情3",
               level: AlertLevel.SS,
               duration: 5000
           ); 
            _alertManager.AddAlert(
               id: "alert1",
               message: "发现火情4",
               level: AlertLevel.SS,
               duration: 2000
           );  
            _alertManager.AddAlert(
               id: "alert1",
               message: "发现火情5",
               level: AlertLevel.SS,
               duration: 1000
           );
            _alertManager.AddAlert(
              id: "alert99",
              message: "发现火情99",
              level: AlertLevel.A,
              duration: 1000
          );
            _alertManager.AddAlert(
               id: "alert1",
               message: "发现火情6",
               level: AlertLevel.SS,
               duration: 5000
           );
           
            // 解决异常
               _alertManager.ResolveAlert("alert99");
        }
    }

}


